package ravenmocker.xml;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLParser {

	public LinkedHashMap<String, List<LinkedHashMap<String, String>>> parse(File file) {
		LinkedHashMap<String, List<LinkedHashMap<String, String>>>  map = new LinkedHashMap<String, List<LinkedHashMap<String, String>>>();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(file);
			map = parseDocument(doc);
		} catch(ParserConfigurationException pce) { pce.printStackTrace(); }
		  catch(SAXException se) { se.printStackTrace(); }
		  catch(IOException ioe) { ioe.printStackTrace(); }
		return map;
	}
	
	private LinkedHashMap<String, List<LinkedHashMap<String, String>>> parseDocument(Document doc) {
		LinkedHashMap<String, List<LinkedHashMap<String, String>>>  map = new LinkedHashMap<String, List<LinkedHashMap<String, String>>>();
		Element root = doc.getDocumentElement();
		NodeList entities = root.getElementsByTagName("entity");
		if (entities != null) {
			for(int i=0; i<entities.getLength(); i++) {
				Element entity = (Element)entities.item(i);
				String entityName = entity.getAttribute("name");
				if(!map.containsKey(entityName)) {
					List<LinkedHashMap<String, String>> list = new ArrayList<LinkedHashMap<String, String>>();
					NodeList attributes = entity.getElementsByTagName("attribute");
					if (attributes != null) {
						for (int j=0; j<attributes.getLength(); j++) {
							LinkedHashMap<String, String> pair = new LinkedHashMap<String, String>();
							Element attribute = (Element)attributes.item(j);
							NamedNodeMap keyValuePair = attribute.getAttributes();
							for(int k=0; k<keyValuePair.getLength(); k++) {
								String key = keyValuePair.item(k).getNodeName();
								String value = keyValuePair.item(k).getNodeValue();
								pair.put(key, value);
							}
							list.add(pair);
						}
					}
					map.put(entityName, list);
				} else {
					System.out.println("Duplicate entities detected: " + entityName);
				}
			}
		}
		return map;
	}
	
}
